package main

import (
	"context"
	"github.com/go-redis/redis"
	_ "github.com/go-sql-driver/mysql"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/logger"
	"github.com/kataras/iris/v12/middleware/recover"
	"github.com/kataras/iris/v12/mvc"
	"time"
	"xorm.io/xorm"
	"xorm.io/xorm/names"
)

var (
	engine *xorm.Engine
	rdb    *redis.Client
)

func main() {
	_ = initDB()
	_ = initRedis()

	app := iris.New()
	app.Use(recover.New())
	app.Use(logger.New())

	mvc.Configure(app.Party("/groups"), GroupHandler)

	err := app.Run(iris.Addr(":8080"))
	if err != nil {
		return
	}
}

func initDB() (err error) {
	dsn := "root:root@tcp(127.0.0.1:3306)/go_db?charset=utf8mb4&parseTime=True"
	if engine, err = xorm.NewEngine("mysql", dsn); err != nil {
		return err
	}
	tbMapper := names.NewPrefixMapper(names.SnakeMapper{}, "t_")
	engine.SetTableMapper(tbMapper)
	if err := engine.Sync2(
		new(SopTask),
		new(SopTaskItem),
		new(Group),
		new(GroupUser),
	); err != nil {
		return err
	}
	engine.ShowSQL(true)
	return engine.Ping()
}

func initRedis() (err error) {
	rdb = redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "",  // no password set
		DB:       0,   // use default DB
		PoolSize: 100, // 连接池大小
	})

	_, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	_, err = rdb.Ping().Result()
	return err
}

func Success(data interface{}) iris.Map {
	return iris.Map{
		"code":    0,
		"message": "Success",
		"data":    data,
	}
}

func Fail(err error) iris.Map {
	return iris.Map{
		"code":    0,
		"message": err.Error(),
		"data":    nil,
	}
}
